//
//  ImagePreviewBrowser.m
//  etionUI
//
//  Created by wangjian on 5/10/13.
//
//

#import "ImagePreviewBrowser.h"

@implementation CImagePreviewBrowser

@synthesize m_delegate;

+ (CGFloat)heightForWidth:(CGFloat)width
{
    NSInteger thumbnailNum = width >= 400 ? 4 : 3;
    CGFloat thumbnailW = (width-(thumbnailNum-1)*IPB_IMAGE_MARGIN)/thumbnailNum;
    return thumbnailW;
}

- (CGRect)imageFrameAtIndex:(NSInteger)index
{
    return CGRectMake(index * (m_imageSize.width+IPB_IMAGE_MARGIN), 0, m_imageSize.width, m_imageSize.height+3);
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        m_scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        m_scrollView.backgroundColor = [UIColor clearColor];
        m_scrollView.delegate = self;
        m_scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:m_scrollView];
        
        m_imageSize = CGSizeMake(frame.size.height, frame.size.height);
   
        m_tipsView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, m_imageSize.width, m_imageSize.height)];
        m_tipsView.backgroundColor = [UIColor clearColor];
        UIImageView *tipsImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tprt_slipright"]];
        tipsImageView.frame = CGRectMake((m_tipsView.width-tipsImageView.image.size.width)/2,
                                         (m_tipsView.height-tipsImageView.image.size.height)/2,
                                         tipsImageView.image.size.width,
                                         tipsImageView.image.size.height);
        [m_tipsView addSubview:tipsImageView];
        [tipsImageView release];
        
        m_arImageViews = [[NSMutableArray alloc] init];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureResponse:)];
        tapGesture.numberOfTapsRequired = 1;
        tapGesture.numberOfTouchesRequired = 1;
        [self addGestureRecognizer:tapGesture];
        [tapGesture release];
    }
    return self;
}

- (NSInteger)numberOfImageViews
{
    return [m_delegate numberOfImagesInimagePreviewBrowser:self];
}

- (NSInteger)firstImageViewIndex
{
    NSInteger index = m_scrollView.contentOffset.x/(m_imageSize.width+IPB_IMAGE_MARGIN);
    if (m_scrollView.contentOffset.x - index * (m_imageSize.width+IPB_IMAGE_MARGIN) > m_imageSize.width/2.0f+IPB_IMAGE_MARGIN) {
        index ++;
    }
    return index;
}

- (UIImage *)imageForSource:(id)source
{
    UIImage *image = nil;
    if ([source isKindOfClass:[NSString class]])
    {
        if ([source rangeOfString:@"/"].length > 0)
        {
            image = [UIImage imageWithContentsOfFile:source];
        }
        else
        {
            image = [UIImage imageNamed:source];
        }
    }
    else if ([source isKindOfClass:[UIImage class]])
    {
        image = source;
    }
    
    if (image == nil)
    {
        image = [UIImage imageNamed:@"image_error.png"];
    }
    return [UIImage imageFromImage:image size:m_imageSize fillStyle:EImageFillStyleStretchByCenterScale];
}

- (void)reloadImages
{
    NSInteger imageNum = [self numberOfImageViews];
    
    for (UIView *view in m_arImageViews)
    {
        [view removeFromSuperview];
    }
    [m_arImageViews removeAllObjects];
    if (m_attachedView != nil)
    {
        [m_attachedView removeFromSuperview];
    }
    [m_tipsView removeFromSuperview];
    
    for (NSUInteger i=0; i<imageNum; i++)
    {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:[self imageFrameAtIndex:i]];
        imageView.image = [self imageForSource:[m_delegate imagePreviewBrowser:self sourceAtIndex:i]];
        [m_arImageViews addObject:imageView];
//        imageView.frame = [self imageFrameAtIndex:i];
        [m_scrollView addSubview:imageView];
        [imageView release];
    }
    m_scrollView.contentOffset = CGPointZero;
    if (m_arImageViews.count > 0)
    {
        m_scrollView.contentSize = CGSizeMake((m_arImageViews.count-1)*(m_imageSize.width+IPB_IMAGE_MARGIN)+m_scrollView.width, m_scrollView.height);
    }
    else
    {
        m_scrollView.contentSize = CGSizeMake(m_scrollView.width-(m_imageSize.width+IPB_IMAGE_MARGIN), m_scrollView.height);
    }
    
    [self addAttachedView];
    
    m_tipsView.frame = [self imageFrameAtIndex:imageNum];
    [m_scrollView addSubview:m_tipsView];
    [self resetTipsViewAlpha];
}

- (void)reloadImageAtIndex:(NSInteger)index
{
    UIImageView *imageView = [m_arImageViews objectAtIndex:index];
    imageView.image = [self imageForSource:[m_delegate imagePreviewBrowser:self sourceAtIndex:index]];
}

- (void)moveToIndex:(NSInteger)index
{
    [m_scrollView setContentOffset:CGPointMake(index * (m_imageSize.width + IPB_IMAGE_MARGIN), 0) animated:YES];
}

- (void)insertImageAtIndex:(NSInteger)index
{
    for (NSInteger i=index; i<m_arImageViews.count; i++)
    {
        UIImageView *imageView = [m_arImageViews objectAtIndex:i];
        imageView.frame = CGRectOffset(imageView.frame, m_imageSize.width + IPB_IMAGE_MARGIN, 0);
    }
    m_scrollView.contentSize = CGSizeMake(m_scrollView.contentSize.width+m_imageSize.width+IPB_IMAGE_MARGIN, m_scrollView.contentSize.height);
    
    @autoreleasepool
    {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:[self imageFrameAtIndex:index]];
        imageView.image = [self imageForSource:[m_delegate imagePreviewBrowser:self sourceAtIndex:index]];
        [m_arImageViews insertObject:imageView atIndex:index];
        imageView.frame = [self imageFrameAtIndex:index];
        [m_scrollView addSubview:imageView];
        [imageView release];
    }
    
    [self resetAttachedViewFrame];
    
    m_tipsView.frame = [self imageFrameAtIndex:m_arImageViews.count];
    [self resetTipsViewAlpha];
}

- (void)deleteImageAtIndex:(NSInteger)index
{
    if (index < [self firstImageViewIndex])
    {
        m_scrollView.contentOffset = CGPointMake(m_scrollView.contentOffset.x - (m_imageSize.width + IPB_IMAGE_MARGIN), m_scrollView.contentOffset.y);
    }
    m_scrollView.contentSize = CGSizeMake(m_scrollView.contentSize.width - (m_imageSize.width + IPB_IMAGE_MARGIN), m_scrollView.contentSize.height);
    
    for (NSInteger i=index+1; i<m_arImageViews.count; i++)
    {
        UIImageView *imageView = [m_arImageViews objectAtIndex:i];
        imageView.frame = CGRectMake(imageView.left - (m_imageSize.width + IPB_IMAGE_MARGIN), imageView.top, imageView.width, imageView.height);
    }
    UIImageView *delImageView = [m_arImageViews objectAtIndex:index];
    [delImageView removeFromSuperview];
    [m_arImageViews removeObjectAtIndex:index];
    
    [self resetAttachedViewFrame];
    
    m_tipsView.frame = [self imageFrameAtIndex:m_arImageViews.count];
    [self resetTipsViewAlpha];
}

- (void)addAttachedView
{
    m_attachedView = [m_delegate imagePreviewBrowserAttachedView:self];
    if (m_attachedView != nil)
    {
        m_scrollView.frame = CGRectMake(0, 0, self.width - m_imageSize.width - IPB_IMAGE_MARGIN, self.height);
        m_scrollView.contentSize = CGSizeMake(m_scrollView.contentSize.width - (m_imageSize.width+IPB_IMAGE_MARGIN), m_scrollView.contentSize.height);
        [self addSubview:m_attachedView];
        [self resetAttachedViewFrame];
    }
}

- (void)deleteAttachedView
{
    if (m_attachedView != nil)
    {
        [m_attachedView removeFromSuperview];
        m_attachedView = nil;
        m_scrollView.frame = self.bounds;
        m_scrollView.contentSize = CGSizeMake(m_scrollView.contentSize.width + (m_imageSize.width+IPB_IMAGE_MARGIN), m_scrollView.contentSize.height);
    }
}

- (UIView *)cellViewAtIndex:(NSUInteger)index
{
    if (index >= m_arImageViews.count)
    {
        return nil;
    }
    return [m_arImageViews objectAtIndex:index];
}

-(void)tapGestureResponse:(UITapGestureRecognizer *)tapgesture
{
    CGPoint point = [tapgesture locationInView:self];
    
    if (m_attachedView != nil && CGRectContainsPoint(m_attachedView.frame, point))
    {
        if ([m_delegate respondsToSelector:@selector(imagePreviewBrowserAttachedViewClicked:)])
        {
            [m_delegate imagePreviewBrowserAttachedViewClicked:self];
            return;
        }
    }
    
    NSInteger index = (point.x + m_scrollView.contentOffset.x) / (m_imageSize.width + IPB_IMAGE_MARGIN);
    if (index < m_arImageViews.count)
    {
        if ([m_delegate respondsToSelector:@selector(imagePreviewBrowser:clickImageAt:)])
        {
            [m_delegate imagePreviewBrowser:self clickImageAt:index];
        }
    }
}

#pragma mark scroll view delegate

- (void)resetTipsViewAlpha
{
    NSUInteger exNum = m_arImageViews.count > 3 ? m_arImageViews.count - 3 : 0;
    if (m_attachedView != nil || m_scrollView.contentOffset.x < exNum * (m_imageSize.width+IPB_IMAGE_MARGIN) + m_imageSize.width/3)
    {
        m_tipsView.alpha = 0.0;
    }
    else
    {
        if (m_scrollView.contentOffset.x > m_imageSize.width + exNum * (m_imageSize.width+IPB_IMAGE_MARGIN))
        {
            m_tipsView.alpha = 1.0;
        }
        else
        {
            m_tipsView.alpha = (m_scrollView.contentOffset.x - exNum * (m_imageSize.width+IPB_IMAGE_MARGIN) - m_imageSize.width/3) / (m_imageSize.width*2/3);
        }
    }
}

- (void)resetAttachedViewFrame
{
    CGFloat x = m_arImageViews.count*(m_imageSize.width+IPB_IMAGE_MARGIN)-m_scrollView.contentOffset.x;
    if (x >= self.width - m_imageSize.width)
    {
        x = self.width - m_imageSize.width;
    }
    m_attachedView.frame = CGRectMake(x, 0, m_attachedView.width, m_attachedView.height);
}

- (void)adjustScrollViewOffset
{
    NSUInteger index = m_scrollView.contentOffset.x / (m_imageSize.width + IPB_IMAGE_MARGIN);
    CGFloat offset = m_scrollView.contentOffset.x - index * (m_imageSize.width + IPB_IMAGE_MARGIN);
    if (offset > 0)
    {
        if (offset > m_imageSize.width/2.0f+IPB_IMAGE_MARGIN)
        {
            index++;
        }
        
        CGPoint newOffset = CGPointMake((CGFloat)index * (m_imageSize.width + IPB_IMAGE_MARGIN), 0.0f);
        if (newOffset.x > m_scrollView.contentSize.width - m_scrollView.width)
        {
            newOffset.x = m_scrollView.contentSize.width - m_scrollView.width;
        }
        if (newOffset.x != m_scrollView.contentOffset.x)
        {
            [m_scrollView setContentOffset:newOffset animated:YES];
            m_scrollView.scrollEnabled = NO;
        }
    }
    if ([m_delegate respondsToSelector:@selector(imagePreviewBrowser:scrollTo:)])
    {
        [m_delegate imagePreviewBrowser:self scrollTo:index];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (decelerate == NO)
    {
        [self adjustScrollViewOffset];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self adjustScrollViewOffset];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    m_scrollView.scrollEnabled = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self resetAttachedViewFrame];
    [self resetTipsViewAlpha];
}

- (void)dealloc
{
    [m_tipsView release];
    [m_arImageViews release];
    [m_scrollView release];
    [super dealloc];
}

@end
